/*
	File: D:/works_2/panzer_2010/data/scripts/saucer_body_follow_target.nut
	Author: The Team
*/

		Include("builtin/script/item_ai_behaviour_follow_target.nut")
		Include("data/scripts/cannon.nut")

/*!
	@short	saucer_body
	@author	The Team
*/
class	saucer_body extends BuiltinItemAIBehaviourFollowTarget
{
	project_script		=	0
	look_at				=	0
	saucer_cannon		=	0
	scene				=	0
	shoot_range			=	Mtr(10.0)
	cannon 				=	0
	shoot_timeout		=	0.0
	cannon_switch		=	0

	/*!
		@short	OnUpdate
		Called during the scene update, each frame.
	*/
	function	OnUpdate(item)
	{
		//project_script.SetItemState(item)
		local	_target_pos = ItemGetWorldPosition(target_item)

			look_at = _target_pos.Lerp(0.05, look_at)
			look_at.y = ItemGetWorldPosition(saucer_cannon).y
			ItemSetTarget(saucer_cannon, look_at)

		if (ItemGetWorldPosition(item).Dist(_target_pos) < shoot_range)
		{
			if ((g_clock - shoot_timeout) > SecToTick(Sec(1.0)))
			{
				shoot_timeout = g_clock
				cannon.Fire((cannon_switch == 0)?0.200:-0.200)
				cannon_switch = 1 - cannon_switch
			}
		}
	}

	function	FetchRangeFromHelper(item)
	{
		local	_parent
		_parent = ItemGetParent(item)
		if (ObjectIsValid(_parent))
		{
			print("Turret::FetchRangeFromHelper() found parent item : '" + ItemGetName(_parent) + "'")

			local	_helper
			_helper = ItemGetChild(_parent, "range")
			if (ObjectIsValid(_helper))
			{
				shoot_range = ItemGetScale(_helper).x / 2.0
				ItemActivate(_helper, false)
				print("Turret::FetchRangeFromHelper() found a helper, shoot_range = " + shoot_range.tostring() + " meters.")
			}
		}
	}

	function	OnSetup(item)
	{		
		target_name = "tank"
		project_script = ProjectGetScriptInstance(g_project)

		scene = ItemGetScene(item)
		saucer_cannon = SceneFindItemChild(scene, item, "saucer_cannon")
		look_at = Vector(0,0,0)

		cannon = Cannon(SceneFindItemChild(scene, saucer_cannon, "bullet_out"))
		shoot_timeout = g_clock

		FetchRangeFromHelper(item)
	}
}
